<template>
  <div>
    <!-- 悬浮球 -->
    <div 
      v-if="!isDialogOpen"
      class="ai-floating-ball" 
      :class="{ 'is-dragging': isDragging }"
      :style="floatingBallStyle"
      @mousedown="startDrag"
      @touchstart="startDrag"
      @click="openDialog"
    >
      <div class="ball-icon">
        <el-icon :size="28"><ChatDotRound /></el-icon>
      </div>
      <div class="ball-badge" v-if="unreadCount > 0">{{ unreadCount }}</div>
      <div class="ball-pulse"></div>
    </div>

    <!-- AI客服对话框 -->
    <el-dialog
      v-model="isDialogOpen"
      :title="dialogTitle"
      width="80%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      custom-class="ai-customer-service-dialog"
      @close="handleDialogClose"
    >
      <div class="dialog-content" v-if="isDialogOpen">
        <AICustomerService ref="aiServiceRef" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { ChatDotRound } from '@element-plus/icons-vue';
import AICustomerService from '@/views/wms/AICustomerService/AICustomerService.vue';

// 悬浮球位置
const ballPosition = ref({
  x: window.innerWidth - 80,
  y: window.innerHeight - 150
});

// 拖拽状态
const isDragging = ref(false);
const dragStartPos = ref({ x: 0, y: 0 });

// 对话框状态
const isDialogOpen = ref(false);

// 未读消息数
const unreadCount = ref(0);

// 对话框标题
const dialogTitle = ref('智能AI客服（曾庆优）');

// AI服务组件引用
const aiServiceRef = ref(null);

// 悬浮球样式
const floatingBallStyle = computed(() => ({
  left: `${ballPosition.value.x}px`,
  top: `${ballPosition.value.y}px`
}));

/**
 * 开始拖拽
 */
const startDrag = (e) => {
  isDragging.value = true;
  
  const clientX = e.type === 'touchstart' ? e.touches[0].clientX : e.clientX;
  const clientY = e.type === 'touchstart' ? e.touches[0].clientY : e.clientY;
  
  dragStartPos.value = {
    x: clientX - ballPosition.value.x,
    y: clientY - ballPosition.value.y
  };

  document.addEventListener('mousemove', onDrag);
  document.addEventListener('mouseup', stopDrag);
  document.addEventListener('touchmove', onDrag);
  document.addEventListener('touchend', stopDrag);
  
  e.preventDefault();
};

/**
 * 拖拽中
 */
const onDrag = (e) => {
  if (!isDragging.value) return;

  const clientX = e.type === 'touchmove' ? e.touches[0].clientX : e.clientX;
  const clientY = e.type === 'touchmove' ? e.touches[0].clientY : e.clientY;

  let newX = clientX - dragStartPos.value.x;
  let newY = clientY - dragStartPos.value.y;

  // 边界限制
  const maxX = window.innerWidth - 60;
  const maxY = window.innerHeight - 60;
  
  newX = Math.max(0, Math.min(newX, maxX));
  newY = Math.max(0, Math.min(newY, maxY));

  ballPosition.value = { x: newX, y: newY };
};

/**
 * 停止拖拽
 */
const stopDrag = () => {
  isDragging.value = false;
  
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
  document.removeEventListener('touchmove', onDrag);
  document.removeEventListener('touchend', stopDrag);
  
  // 吸附到边缘
  snapToEdge();
};

/**
 * 吸附到屏幕边缘
 */
const snapToEdge = () => {
  const windowWidth = window.innerWidth;
  const threshold = windowWidth / 2;
  
  if (ballPosition.value.x < threshold) {
    ballPosition.value.x = 20;
  } else {
    ballPosition.value.x = windowWidth - 80;
  }
};

/**
 * 打开对话框
 */
const openDialog = () => {
  if (isDragging.value) return;
  isDialogOpen.value = true;
  unreadCount.value = 0;
};

/**
 * 关闭对话框
 */
const handleDialogClose = () => {
  isDialogOpen.value = false;
};

/**
 * 窗口大小改变时调整位置
 */
const handleResize = () => {
  const maxX = window.innerWidth - 60;
  const maxY = window.innerHeight - 60;
  
  ballPosition.value.x = Math.min(ballPosition.value.x, maxX);
  ballPosition.value.y = Math.min(ballPosition.value.y, maxY);
};

/**
 * 组件挂载
 */
onMounted(() => {
  window.addEventListener('resize', handleResize);
  
  // 从localStorage恢复位置
  const savedPosition = localStorage.getItem('ai-floating-ball-position');
  if (savedPosition) {
    try {
      ballPosition.value = JSON.parse(savedPosition);
    } catch (e) {
      console.error('恢复悬浮球位置失败:', e);
    }
  }
});

/**
 * 组件卸载
 */
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  
  // 保存位置
  localStorage.setItem('ai-floating-ball-position', JSON.stringify(ballPosition.value));
});
</script>

<style scoped lang="less">
/* 悬浮球 */
.ai-floating-ball {
  position: fixed;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.4);
  cursor: pointer;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  
  &:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 30px rgba(102, 126, 234, 0.6);
  }
  
  &:active {
    transform: scale(0.95);
  }
  
  &.is-dragging {
    cursor: grabbing;
    transform: scale(1.05);
    box-shadow: 0 8px 40px rgba(102, 126, 234, 0.5);
  }
}

.ball-icon {
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  z-index: 2;
}

/* 未读消息角标 */
.ball-badge {
  position: absolute;
  top: -2px;
  right: -2px;
  min-width: 18px;
  height: 18px;
  background: #f56c6c;
  border-radius: 9px;
  color: #fff;
  font-size: 11px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 4px;
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.4);
  z-index: 3;
  animation: badge-bounce 0.5s ease;
}

@keyframes badge-bounce {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
}

/* 脉冲动画 */
.ball-pulse {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: inherit;
  opacity: 0.6;
  z-index: 1;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 0.6;
  }
  50% {
    transform: scale(1.2);
    opacity: 0.3;
  }
  100% {
    transform: scale(1);
    opacity: 0.6;
  }
}

/* 对话框样式 */
:deep(.ai-customer-service-dialog) {
  border-radius: 12px;
  
  .el-dialog__header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    border-radius: 12px 12px 0 0;
    padding: 20px;
    
    .el-dialog__title {
      color: #fff;
      font-size: 18px;
      font-weight: bold;
    }
    
    .el-dialog__headerbtn {
      .el-dialog__close {
        color: #fff;
        font-size: 20px;
        
        &:hover {
          color: #f0f0f0;
        }
      }
    }
  }
  
  .el-dialog__body {
    padding: 0;
    height: 80vh;
    overflow: hidden;
  }
}

.dialog-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.ai-customer-service-dialog) {
    width: 95% !important;
    margin: 20px auto;
    
    .el-dialog__body {
      height: 70vh;
    }
  }
  
  .ai-floating-ball {
    width: 50px;
    height: 50px;
    
    .ball-icon {
      :deep(.el-icon) {
        font-size: 24px;
      }
    }
  }
}

/* 平滑过渡 */
.ai-floating-ball {
  transition: left 0.3s cubic-bezier(0.4, 0, 0.2, 1),
              top 0.3s cubic-bezier(0.4, 0, 0.2, 1),
              transform 0.2s ease,
              box-shadow 0.2s ease;
}
</style>

